using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;

namespace LWCodePastPlugin
{
    [ProgId("Source code Snippet")]
    public partial class frmSource : Form
    {
        public frmSource()
        {
            InitializeComponent();
            DataUpdate();

            cbLinesNum.Checked = AppSettings.Default.LineEnum;
            cbWrap.Checked = AppSettings.Default.LineWrap;
            cbHeader.Checked = AppSettings.Default.HeaderFormat;
            nmLines.Value = AppSettings.Default.LineEnumStart;
            cbPalette.Checked = AppSettings.Default.UsePalette;

            FormattedOutput = getOptionText();
            
            
        }

        void DataUpdate()
        {
            btOK.Enabled = Clipboard.ContainsData(DataFormats.Rtf);
            if (btOK.Enabled)
            {
                tmp_path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/preview.htm";
                oData = Clipboard.GetData(DataFormats.Rtf);
                try
                {
                    actCode = RTF2HTML.Convert(oData.ToString());
                }
                catch {
                    MessageBox.Show("Error occured while trying to retrive clipboard content. Operation canceled.", "Bad clipboard content", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                
            }
            label1.Visible = !btOK.Enabled;
        }
       
        protected override void OnActivated(EventArgs e)
        {
            
            if (oData == null)
                oData = "";
            if (Clipboard.ContainsData(DataFormats.Rtf) && Clipboard.GetData(DataFormats.Rtf).ToString() != oData.ToString())
            {
                oData = Clipboard.GetData(DataFormats.Rtf);

                if (MessageBox.Show("Data inside your clipboard has been changed.\r\nDo you want to override code snippet with new data?", "Clipboard data change detected", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    DataUpdate();
                    FormattedOutput = getOptionText();
                }
            }
            base.OnActivated(e);
            
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (tmp_path != string.Empty && File.Exists(tmp_path))
                File.Delete(tmp_path);

             AppSettings.Default.HeaderFormat = cbHeader.Checked;
             AppSettings.Default.LineEnum = cbLinesNum.Checked;
             AppSettings.Default.LineWrap = cbWrap.Checked;
             AppSettings.Default.LineEnumStart = nmLines.Value;
             AppSettings.Default.UsePalette = cbPalette.Checked;
             AppSettings.Default.Save();

            base.OnClosing(e);
        }

        string actCode = string.Empty;
        string tmp_path = string.Empty;
        private string m_frm_output = string.Empty;
        object oData = null;

        public string FormattedOutput
        {
            get { return "<P>" + m_frm_output + "</P><p>&nbsp;</p>"; }
            private set {
                if (tmp_path != string.Empty)
                {
                    m_frm_output = value;

                    using (StreamWriter fs = new StreamWriter(tmp_path))
                    {
                        fs.Write("<html><body>" + m_frm_output + "</body></html>");
                        fs.Close();
                    }

                    if (webBrowser1.Document == null)
                        webBrowser1.Navigate(tmp_path);
                    else
                        webBrowser1.Refresh(WebBrowserRefreshOption.Completely);
                }
                
            }
        }

        private void btOK_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        string getOptionText()
        {
            if (actCode != string.Empty)
            {
                StringBuilder sb = new StringBuilder();
                if (cbLinesNum.Checked)
                {
                    string[] outp = actCode.Replace(@"\r\n", "\r").Split('\r');

                    int offset = 0;
                    for (int i = 0; i < outp.Length; i++)
                    {
                        if (outp[i].Trim() == string.Empty)
                        {
                            sb.Append("<br/>");
                            offset++;
                        }
                        else
                        {
                            string w1 =string.Empty;
                            string w2 = string.Empty;
                            if (cbWrap.Checked)
                            {
                                w1 = "<nobr>";
                                w2 = "</nobr>";
                            }
                            sb.Append(string.Format("{2}<font color='Black'>{0}:</font>&nbsp;&nbsp;{1}{3}<br/>", 
                                nmLines.Value + i - offset, 
                                outp[i].Replace("\r",string.Empty).Replace("\n",string.Empty),
                                w1,w2));
                        }
                    }
                }
                else
                {
                    sb.Append(actCode);
                }

                sb.Insert(0, "<pre>");
                sb.Append("</pre");

                if (cbHeader.Checked)
                { 
                    string before = "<DIV style='margin-left:4px; margin-right:4px; padding:0px; background:#808080;'>"
                    +"<DIV style='top:-2px; left:-2px; position: relative; background: #fff; color: black; border: 1px solid #2E595C;'>"
                    +"<DIV style='background:#3F73B6; color:white; border:1px solid blue; width:100%;'><SPAN style='WIDTH: 100%'>Code Snippet</SPAN></DIV>";
                    string after = "</DIV></DIV>";
                    sb.Insert(0, before);
                    sb.Append(after);
                }

                return sb.ToString();
            }
            return string.Empty;
        }

        private void cbHeader_CheckedChanged(object sender, EventArgs e)
        {
            FormattedOutput = getOptionText();
        }

        private void cbLines_CheckedChanged(object sender, EventArgs e)
        {
            nmLines.Enabled = cbLinesNum.Checked;
            FormattedOutput = getOptionText();
        }

        private void nmLines_ValueChanged(object sender, EventArgs e)
        {
            FormattedOutput = getOptionText();
        }

        private void cbWrap_CheckedChanged(object sender, EventArgs e)
        {
            FormattedOutput = getOptionText();
        }

        private void frmSource_HelpButtonClicked(object sender, CancelEventArgs e)
        {
            using (frmAbout a = new frmAbout())
            {
                a.ShowDialog();
            }
            e.Cancel = true;
        }

        private void cbPalette_CheckedChanged(object sender, EventArgs e)
        {
            AppSettings.Default.UsePalette = cbPalette.Checked;
            DataUpdate();
            FormattedOutput = getOptionText();
        }
	
    }
}